/*
* Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: btclient.cpp.
*/

#include <qbluetoothsocket.h>

#include "btclient.h"

BtClient::BtClient(QObject *parent) :
    QObject(parent), m_socket(0)
{
}

BtClient::~BtClient()
{
    delete m_socket;
}

void BtClient::startClient(const QBluetoothAddress &address, quint16 port)
{
    if (m_socket)
        return;

    // Connect to service
    m_socket = new QBluetoothSocket(QBluetoothSocket::RfcommSocket);
    m_socket->connectToService( address, port, QIODevice::ReadWrite );

    connect(m_socket, SIGNAL(connected()), this, SLOT(handleConnected()));
    connect(m_socket, SIGNAL(readyRead()), this, SLOT(readSocket()));
    connect(m_socket, SIGNAL(disconnected()), this, SIGNAL(connectionClosed()));
}

void BtClient::closeClient()
{
    if ( m_socket )
    {
        m_socket->disconnectFromService();
        m_socket->deleteLater();
        m_socket = 0;
    }
}

void BtClient::writeSocket(const QByteArray &sharedData)
{
    qDebug() << "BtClient::writeSocket";
    if ( m_socket )
    {
        qDebug() << "BtClient::writeSocket - socket found, write data";
        m_socket->write(sharedData);
    }
}

void BtClient::readSocket()
{
    qDebug() << "BtClient::readSocket";
    if ( m_socket )
    {
        qDebug() << "BtClient::readSocket - socket found, read data";
        if ( m_socket->bytesAvailable() )
        {
            emit messageReceived( m_socket->readAll() );
        }
    }
}

void BtClient::handleConnected()
{
    emit connected(m_socket->peerName());
}
